﻿CREATE TRIGGER yaf_Forum_update
ON dbo.yaf_Forum
FOR UPDATE
AS
    BEGIN
        IF UPDATE(LastTopicID) OR UPDATE(LastMessageID)
        BEGIN
            -- recursively update the forum
            DECLARE  @ParentID INT
            SET @ParentID = (SELECT TOP 1 ParentID
                             FROM   inserted)
            WHILE (@ParentID IS NOT NULL)
            BEGIN
                UPDATE a
                SET    a.LastPosted = b.LastPosted,
                       a.LastTopicID = b.LastTopicID,
                       a.LastMessageID = b.LastMessageID,
                       a.LastUserID = b.LastUserID,
                       a.LastUserName = b.LastUserName
                FROM   yaf_Forum a,
                       inserted b
                WHERE  a.ForumID = @ParentID
                AND ((a.LastPosted < b.LastPosted)
                      OR a.LastPosted IS NULL);
                SET @ParentID = (SELECT ParentID
                                 FROM   yaf_Forum
                                 WHERE  ForumID = @ParentID)
            END
        END
    END


